package me.eleme.anubis.openapi.demo;

import com.alibaba.fastjson.JSON;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import lombok.extern.slf4j.Slf4j;
import me.eleme.anubis.openapi.api.exception.ServiceException;
import me.eleme.anubis.openapi.config.Config;
import me.eleme.anubis.openapi.config.oauth.response.Token;
import me.eleme.anubis.openapi.oauth.OauthClient;
import me.eleme.anubis.openapi.utils.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘志永
 */
@Slf4j
public class HttpServerDemo {

    private final static Config CONFIG;

    private static Token TOKEN = null;

    private final static OauthClient CLIENT;
    /**
     * 设置是否沙箱环境
     */
    private static final boolean IS_SANDBOX = false;

    private static final String AND_STR = "&";
    private static final String EQUAL_STR = "=";
    private static final String CHARSET_NAME = "UTF-8";

    /**
     * 设置APP KEY
     */
    private static final String APP_ID = "app id";

    /**
     * 设置APP SECRET
     */
    private static final String SECRET_KEY = "secret key";

    /**
     * 回调地址
     */
    private static final String CALLBACK_URL = "your callback url";


    static {
        CONFIG = new Config(IS_SANDBOX, APP_ID, SECRET_KEY);
        CLIENT = new OauthClient(CONFIG);
        try {
            TOKEN = CLIENT.getTokenByCode("code", "","https://localhost:8899/demo");
        } catch (ServiceException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            start(8899);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void start(Integer port) throws IOException {
        InetSocketAddress address = new InetSocketAddress(port);
        HttpServer server = HttpServer.create(address, 0);
        if (server != null) {
            server.createContext("/demo", new DemoHandler());
            server.setExecutor(null);
            server.start();
        }
    }


    static class DemoHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String query = t.getRequestURI().getQuery();
            String initHtml = rtnHtml();
            if (StringUtils.isEmpty(query)) {
                response(t, initHtml);
                return;
            }
            Map<String, String> stringStringMap = queryToMap(t.getRequestURI().getQuery());
            String code = stringStringMap.get("code");
            if (StringUtils.isEmpty(code)) {
                response(t, initHtml);
                return;
            }
            Token token = null;
            try {
                token = CLIENT.getTokenByCode("Mh8FqMk2zbUZg5GQ7sZizI", "11111","https://localhost:8899/demo");
            } catch (ServiceException e) {
                e.printStackTrace();
            }
            log.error("token：[}", JSON.toJSONString(token));
        }
    }

    private static void response(HttpExchange t, String responseMsg) {
        try {
            t.sendResponseHeaders(HttpURLConnection.HTTP_OK, responseMsg.getBytes().length);
            OutputStream os = t.getResponseBody();
            os.write(responseMsg.getBytes(CHARSET_NAME));
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    private static String rtnHtml() throws IOException {
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("page/demo.html");
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = resourceAsStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        return result.toString(CHARSET_NAME);
    }

    /**
     *
     * @param query url参数字符串
     * @return url转换为map结构
     */
    private static Map<String, String> queryToMap(String query) {
        Map<String, String> result = new HashMap<>(16);
        for (String param : query.split(AND_STR)) {
            String[] pair = param.split(EQUAL_STR);
            if (pair.length > 1) {
                result.put(pair[0], pair[1]);
            } else {
                result.put(pair[0], "");
            }
        }
        return result;
    }

    private static class ResponseResult {
        private Result result;

        public Result getResult() {
            return result;
        }

        public void setResult(Result result) {
            this.result = result;
        }

        static class Result {
            private String oauthUrl;
            private String shopName;

            public String getOauthUrl() {
                return oauthUrl;
            }

            public void setOauthUrl(String oauthUrl) {
                this.oauthUrl = oauthUrl;
            }

            public String getShopName() {
                return shopName;
            }

            public void setShopName(String shopName) {
                this.shopName = shopName;
            }
        }
    }
}
